package com.transcargo.action;

import com.transcargo.db.db;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.sql.SQLException;

/**
 * Date: 17.04.2011
 * Time: 15:51:25
 */
public class AuthAction extends Action {
    protected int User_Id = 0;
    protected void doAuth(HttpServletRequest request) throws ServletException {
        String sessionid = "";
        if (cookies != null) {
          for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("sessionid")) {
              cookie = cookies[i];
            }
          }
        }
        if (cookie != null) {
            sessionid = cookie.getValue();
            db.PreStatement pre;
			try {
				pre = dbase.CreateStatement("SELECT GetSessionUser(?, ?)");
	            pre.Insert(sessionid);
	            pre.Insert(request.getRemoteAddr());
	            list = dbase.execute(pre);
			} catch (SQLException e) {
				throw new ServletException(e.getMessage());
			} catch (Exception e) {
				throw new ServletException(e.getMessage());
			}
            if (list != null) {
                iter = list.iterator();
                if (iter.hasNext()) {
                    String[] ctr = iter.next();
                    if (ctr[0] != null) User_Id = Integer.parseInt(ctr[0]);
                }
            }
       }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        InitActionServlet(request, response);
        doAuth(request);
        if (User_Id <= 0) {
            sendRedirect(response, "auth.jsp");
            return;
        }
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "text/xml; charset=UTF-8");
        processAction(request, response);
    }
}
